package cn.pfz.controller;

import cn.pfz.Service.IDepartmentSerives;
import cn.pfz.annotation.RequiredPermission;
import cn.pfz.domain.Department;
import cn.pfz.domain.JsonResult;
import cn.pfz.query.QueryObject;
import com.github.pagehelper.PageInfo;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("/department")
public class DepartmentController {

    @Autowired
    private IDepartmentSerives is;




    @RequiresPermissions(value = {"department:list","部门列表"},logical = Logical.OR)
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") QueryObject qo){
        PageInfo<Department> list = is.list(qo);
        model.addAttribute("result",list);
        return "department/list";
    }

    @RequiresPermissions(value = {"department:saveOrUpdate","部门新增/编辑"},logical = Logical.OR)
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(Department department){
        if(department.getId()!=null){
            //修改
            is.updateByPrimaryKey(department);
        }else{
            is.insert(department);
        }
        return "redirect:/department/list";
    }

   //自定义的 @RequiredPermission(name = "部门删除", experssion = "department:delete")
    @RequiresPermissions(value = {"department:delete","部门删除"},logical = Logical.OR)
    @ResponseBody
    @RequestMapping ("/delete")
    public JsonResult delete(Long id){
is.deleteByPrimaryKey(id);
        return JsonResult.success(null);
    }

    @RequiresPermissions(value = {"department:exportXls","部门导出"},logical = Logical.OR)
    @RequestMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
//提交一个数据保存到excel的请求 java操作excel文件 需要设定相应头信息
        //在相应头信息里设定保存的文件名 保存类型
        response.setHeader("Content-Disposition","attachment;filename=department.xls");
        //操作excel WorkBook
        Workbook workbook=is.getWrokbook();
        //生成文件
        workbook.write(response.getOutputStream());

    }



}